    <template>

    <div class="app-container" v-if="canList">
        <div class="filter-container">
            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                      placeholder="省区"
                      v-model="listQuery.province">
            </el-input>
            <!--  <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
            placeholder="重量区间"
            v-model="listQuery.weight">
  </el-input>
              <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
            placeholder="价格区间"
            v-model="listQuery.price">
  </el-input>
              <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
            placeholder="首重价格"
            v-model="listQuery.fp">
  </el-input>
              <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
            placeholder="超出价格单价"
            v-model="listQuery.up">
  </el-input>-->

            <div style="display: inline-block">

                <el-button style="margin-left: 10px;" class="filter-item" type="primary" v-waves icon="el-icon-search"
                           @click="handleFilter">查找
                </el-button>
                <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary"
                           v-if="canSave" icon="el-icon-edit">添加
                </el-button>
                <!--<el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download"
                           @click="handleDownload">导出
                </el-button>-->
            </div>
        </div>

        <el-table style="width: 100%" :key='tableKey' :data="list" v-loading="listLoading" border  highlight-current-row>
            <el-table-column align="center" label="序号">
                <template slot-scope="scope">
                    <span>{{scope.row.id}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="省区" width="300">
                <template slot-scope="scope">
                    <span>{{scope.row.province}}</span>
                </template>
            </el-table-column>


            <el-table-column align="center" label="重量区间">
                <template slot-scope="scope">
                    <span>{{scope.row.weight}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="价格区间">
                <template slot-scope="scope">
                    <span>{{scope.row.price}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="首重价格">
                <template slot-scope="scope">
                    <span>{{scope.row.fp}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="超出价格单价">
                <template slot-scope="scope">
                    <span>{{scope.row.up}}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="操作"  class-name="small-padding fixed-width" width="145px">
                <template slot-scope="scope">
                    <el-button type="primary" v-if="canUpdate" size="mini" @click="handleUpdate(scope)">编辑</el-button>
                    <el-button v-if="canSave" size="mini" type="danger"
                               @click="handleDelete(scope)">删除
                    </el-button>
                </template>
            </el-table-column>

        </el-table>

        <div class="pagination-container" style="margin-top: 20px">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px"
                     style='width: 450px; margin-left:50px;'>
                <el-form-item label="省区" prop="province" >
                    <el-select
                            v-model="provinces"
                            multiple
                            @change=""
                            style="width: 100%"
                            placeholder="请选择">
                        <el-option
                                v-for="item in addressList"
                                :key="item.value"
                                :label="item.text"
                                :disabled="item.disable"
                                :value="item.text">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="重量区间" prop="weight">
                    <el-input placeholder="下划线分开如:1_2_3" v-model="temp.weight"></el-input>
                </el-form-item>
                <el-form-item label="价格区间" prop="price">
                    <el-input v-model="temp.price" placeholder="下划线分开如:1_2_3"></el-input>
                </el-form-item>
                <el-form-item label="首重价格" prop="fp">
                    <el-input v-model="temp.fp"></el-input>
                </el-form-item>
                <el-form-item label="超出价格单价" prop="up">
                    <el-input v-model="temp.up"></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialogForm">取消</el-button>
                <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>
                <el-button v-else type="primary" @click="updateData">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<style type="stylus">
    .filter-container {
        /*padding-bottom: 20px;*/
    }

    .filter-item {
        margin-bottom: 10px;
    }

    .filter-item.input {
        /*line-height: 60px*/
        margin-right: 10px;
    }
</style>

<script>
    import {list, save, update, remove} from '@/api/log_rule'
    import waves from '@/directive/waves' // 水波纹指令
    import {provinceList} from "../../../utils/area";

    import {mapGetters} from 'vuex'
    import {hasAuth} from '@/utils/auth'

    export default {
        name: 'test',
        directives: {
            waves
        },
        data() {
            return {
                provinces:null,
                tableKey: 0,
                list: [],
                total: null,
                listLoading: true,
                listQuery: {
                    page: 1,
                    limit: 20,
                    order: 'id desc'
                    ,
                    province: null
                    ,
                    weight: null
                    ,
                    price: null
                    ,
                    fp: null
                    ,
                    up: null
                },
                temp:
                    {
                        id: null, province: null, weight: null, price: null, fp: null, up: null
                    }
                ,
                dialogFormVisible: false,
                dialogStatus:
                    '',
                textMap:
                    {
                        update: '修改',
                        create:
                            '新增'
                    }
                ,
                rules:
                    {
                        province: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        weight: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        price: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        fp: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        up: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                    }
                ,
                downloadLoading: false,
                qData:
                    {
                        token: '',
                        key:
                            ''
                    }
            }
        },
        created() {
            this.getList()
        },
        computed: {

            ...mapGetters([
                'perms'
            ]),
            addressList() {
                this.list.forEach(item=>{
                    //非当前选中列
                    if(this.temp&&this.temp.id != item.id){
                        item.province.split("_").forEach(p=>{
                            provinceList.forEach(ad=>{
                                if(p==ad.text){

                                    ad.disable = true
                                }
                            })
                        })
                    }
                })
                //去除
                return provinceList
            },
            canSave() {
                return hasAuth(this.perms, 'log:rule:save')
            },
            canDelete() {
                return hasAuth(this.perms, 'log:rule:delete')
            },
            canUpdate() {
                return hasAuth(this.perms, 'log:rule:update')
            },
            canList() {
                return hasAuth(this.perms, 'log:rule:list')
            }
        },
        methods: {
            getProvinces(){
                if(this.temp.province)  {
                    return this.temp.province.split("_")
                }
                return  []
            },
            getProvince(){
              let str = '';
              this.provinces.forEach(p=>{
                  str+=p+'_'
              })
                return str.substr(0,str.length-1)
            },
            getList() {
                this.listLoading = true
                list(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.total = response.data.total
                    this.listLoading = false
                })
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            handleSizeChange(val) {
                this.listQuery.limit = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            handleModifyStatus(row, status) {
                this.$message({
                    message: '操作成功',
                    type: 'success'
                })
                row.status = status
            },
            beforeFormShow(row) {
                this.resetTemp(row) // 更新数据
                // 存在图片

            },
            afterFormShow(row) {

            },
            beforeFormCommit() {
                this.temp.province= this.getProvince()
            },
            resetTemp(row) {

                this.temp = {}
                this.provinces = []
                if (row) {
                    this.temp = Object.assign({}, row) // copy obj
                    this.provinces = this.getProvinces()
                }

            },
            handleCreate() {
                this.beforeFormShow()
                this.resetTemp()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.afterFormShow()
                    this.$refs['dataForm'].clearValidate()
                })
            },
            handleDelete(scope) {
                this.index = scope.$index
                // this.beforeFormShow(scope.row)
                // this.temp = Object.assign({}, row) // copy obj
                this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // this.$message({
                    //   type: 'success',
                    //   message: '删除成功!'
                    // })
                    this.deleteData()
                }).catch(() => {
                    this.$message({
                        type: 'error',
                        message: '删除失败'
                    })
                })
            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            save(this.temp).then(res => {
                                this.temp = res.data
                                this.list.unshift(this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '创建成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            deleteData() {
                // const ids = [this.temp.id]
                const ids = [this.list[this.index].id]
                remove({ids: ids}).then(res => {
                    // 从当前队列中移除
                    this.list.splice(this.index, 1)
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                })
            },
            handleUpdate(scope) {
                this.index = scope.$index
                this.beforeFormShow(scope.row)
                this.dialogStatus = 'update'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            update(this.temp).then(() => {
                                this.list.splice(this.index, 1, this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '更新成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            closeDialogForm() {
                this.dialogFormVisible = false
            },
            handleDownload() {
                this.downloadLoading = true
                import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = [
                        '序号'
                        ,
                        '省区'
                        ,
                        '重量区间'
                        ,
                        '价格区间'
                        ,
                        '首重价格'
                        ,
                        '超出价格单价'
                    ]
                    const filterVal = ['id'
                        , 'province'
                        , 'weight'
                        , 'price'
                        , 'fp'
                        , 'up'
                    ]
                    const data = this.formatJson(filterVal, this.list)
                    excel.export_json_to_excel({
                        header: tHeader,
                        data,
                        filename: 'table-list'
                    })
                    this.downloadLoading = false
                })
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                        return v[j]
                    }
                ))
            },
        }
    }
</script>
